﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace WebSites.Controllers
{
    public class AppActionAttributeFilter: ActionFilterAttribute
    {
        public string Message { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //Log("OnActionExecuting", filterContext.RouteData);
            string actionName = filterContext.ActionDescriptor.ActionName;
            bool isAjax = filterContext.HttpContext.Request.IsAjaxRequest();
            if (actionName == "LogOff")
                //ToLogin(filterContext);
                return;
            else
            {
                if (filterContext.HttpContext.Session["UserID"] == null)
                {
                    //filterContext.HttpContext.Response.Write("<script type='text/javascript' src='~/scripts/login.js'></script>");
                    ToLogin(filterContext);
                }
            }
            //base.OnActionExecuting(filterContext);
        }

        private void ToLogin(ActionExecutingContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var jsonRes = new JsonResult();
                jsonRes.Data = new { status = 400, msg = "您未登录或者登录已失效!" };
                jsonRes.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.StatusCode = 400;
                filterContext.HttpContext.Response.StatusDescription = "BadLogin";
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                filterContext.Result = jsonRes;

            }
            else
            {
                ActionResult res = new RedirectResult("/");
                filterContext.HttpContext.Response.Clear();
                filterContext.HttpContext.Response.StatusCode = 400;
                filterContext.HttpContext.Response.StatusDescription = "BadLogin";
                filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
                filterContext.Result = res;
            }
        }

    }
}